package com.cheyunkeji.er.activity.evaluate;

import android.content.Intent;
import android.graphics.Color;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.cheyun.netsalev3.R;
import com.cheyun.netsalev3.MyApplication;
import com.cheyunkeji.er.adapter.citymodel.CarSourceCitySortAdapter;
import com.cheyunkeji.er.adapter.evaluate.CarSourceCitySelecterAdapter;
import com.cheyunkeji.er.base.BaseActivity;
import com.cheyunkeji.er.bean.evaluate.CarInfo;
import com.cheyunkeji.er.http.ApiClient;
import com.cheyunkeji.er.http.HttpConstants;
import com.cheyunkeji.er.http.RespCallback;
import com.cheyunkeji.er.utils.CarSourceCityPinyinComparator;
import com.cheyunkeji.er.utils.PinyinUtils;
import com.cheyunkeji.er.view.SToast;
import com.cheyunkeji.er.view.TopBar;
import com.cheyunkeji.er.view.cityview.SideBar;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Request;

public class CarSourceCitySelectActivity extends BaseActivity implements AdapterView.OnItemClickListener, SideBar.OnTouchingLetterChangedListener {


    private static final String TAG = CarSourceCitySelectActivity.class.getSimpleName();
    @BindView(R.id.v_topbar)
    TopBar vTopbar;
    @BindView(R.id.lv_content)
    ListView lvContent;
    @BindView(R.id.activity_car_source_city_select)
    LinearLayout activityCarSourceCitySelect;
    @BindView(R.id.sidebar)
    SideBar sidebar;

    private ArrayList<CarInfo.CarSourceCity> dataList;

    private final int LEVEL_PROVINCE = 1, LEVEL_CITY = 2;

    private int CURRENT_LIST_DATA_LEVEL = LEVEL_PROVINCE;

    private CarSourceCitySelecterAdapter adapter;

    private CarInfo.CarSourceCity selectedProvince;
    private CarSourceCitySortAdapter sortAdapter ;


    @Override
    protected void init() {
        setContentView(R.layout.er_activity_car_source_city_select);
        ButterKnife.bind(this);
    }

    @Override
    protected void initView() {

        vTopbar.setTitle("选择省份");
        vTopbar.setLeftBack();

        dataList = new ArrayList<>();
        adapter = new CarSourceCitySelecterAdapter(dataList, this);
        lvContent.setAdapter(adapter);

        lvContent.setOnItemClickListener(this);
    }

    @Override
    protected void initData() {

        loadData(String.valueOf(LEVEL_PROVINCE), "");

    }

    private void loadData(String level, String upId) {

        HashMap<String, String> params = new HashMap<>();
        //      params.put("authkey", UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());//        params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(), ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());
        params.put("level", level);
        params.put("upid", upId);

        ApiClient.postForm(HttpConstants.GET_CAR_SOURCE_CITY_LIST, params, new RespCallback<List<CarInfo.CarSourceCity>>() {
            @Override
            protected void onRequestFailed(String msg) {
                SToast.show(msg);
            }

            @Override
            protected void onSuccess(List<CarInfo.CarSourceCity> data) {

                if( CURRENT_LIST_DATA_LEVEL == LEVEL_PROVINCE ){
                    setProvinceList(data);
                }else {
                    setCityList(data);
                }
            }

            @Override
            public void onBefore(Request request, int id) {
                showDialog();
            }

            @Override
            public void onAfter(int id) {
                dismissDialog();
            }
        });

    }

    private void setCityList(List<CarInfo.CarSourceCity> data) {

        if(sidebar.getVisibility() == View.VISIBLE){
            sidebar.setVisibility(View.GONE);
        }

        dataList.clear();
        dataList.addAll(data);
        lvContent.setAdapter(adapter);

    }


    private void setProvinceList(List<CarInfo.CarSourceCity> data) {

        if( null == data ){
            return ;
        }

        dataList.addAll(data);

//      设置首字母
        for(int i = 0 ; i < dataList.size() ;i++){
            dataList.get(i).setLetter(String.valueOf(PinyinUtils.getPingYin(dataList.get(i).getName()).charAt(0)).toUpperCase());
        }

        ArrayList<String> letterList = new ArrayList<>();

        for (int i = 0; i < dataList.size(); i++) {
            if (dataList.get(i).getLetter().matches("[A-Z]") && !letterList.contains(dataList.get(i).getLetter())) {
                letterList.add(dataList.get(i).getLetter());
            }
        }

        Collections.sort(letterList);
        sidebar.setIndexText(letterList);
        sidebar.setTextColor(Color.parseColor("#35404d"));
        sidebar.setVisibility(View.VISIBLE);

        Collections.sort(dataList, new CarSourceCityPinyinComparator());

        sortAdapter = new CarSourceCitySortAdapter(this, dataList);
        lvContent.setAdapter(sortAdapter);

        sidebar.setOnTouchingLetterChangedListener(this);
        lvContent.setOnItemClickListener(this);
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        if (CURRENT_LIST_DATA_LEVEL == LEVEL_PROVINCE) {

            CURRENT_LIST_DATA_LEVEL = LEVEL_CITY ;
            loadData(String.valueOf(LEVEL_CITY), dataList.get(position).getId());
            selectedProvince = dataList.get(position);
            CURRENT_LIST_DATA_LEVEL = LEVEL_CITY;
            vTopbar.setTitle("选择城市");


        } else {

            Intent intent = new Intent();
            intent.putExtra("SOURCE_CITY", dataList.get(position));
            if (null != selectedProvince) {
                intent.putExtra("SOURCE_PROVINCE", selectedProvince);
            }
            setResult(RESULT_OK, intent);
            MyApplication.getInstance().removeActivity(this.getClass());
            finish();
        }
    }

    @Override
    public void onTouchingLetterChanged(String s) {

        //该字母首次出现的位置
        int position = sortAdapter.getPositionForSection(s.charAt(0));
        if (position != -1) {
            lvContent.setSelection(position);
        }
    }
}
